<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item :name="'type'" label="用户类型">
								<a-select
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.type"
									allow-clear
									placeholder="请选择类型"
								>
									<a-select-option value="member">会员</a-select-option>
									<a-select-option value="matchmaker">红娘</a-select-option>
									<a-select-option value="partner">合伙人</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'gender'" label="性别">
								<a-select
									v-model:value="searchInfo.gender"
									allow-clear
									placeholder="请选择性别"
									style="width: 90%; margin-left: 8px"
								>
									<a-select-option value="0">男</a-select-option>
									<a-select-option value="1">女</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'phone'" label="手机号码">
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.phone"
									placeholder="请填写手机号码"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'code'" label="用户编码">
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.code"
									placeholder="请填写用户编码"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'height'" label="身高(cm)">
								<a-input-number
									style="width: 40%; margin-left: 8px"
									v-model:value="searchInfo.heightFrom"
									:min="0"
									placeholder="从"
								/>
								<span style="padding: 0 6px">-</span>
								<a-input-number
									style="width: 40%"
									v-model:value="searchInfo.heightTo"
									:min="searchInfo.heightFrom || 0"
									placeholder="到"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'age'" label="年龄">
								<a-input-number
									style="width: 40%; margin-left: 8px"
									v-model:value="searchInfo.ageFrom"
									:min="0"
									placeholder="从"
								/>
								<span style="padding: 0 6px">-</span>
								<a-input-number
									style="width: 40%"
									v-model:value="searchInfo.ageTo"
									:min="searchInfo.ageFrom || 0"
									placeholder="到"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'weight'" label="体重(kg)">
								<a-input-number
									style="width: 40%; margin-left: 8px"
									v-model:value="searchInfo.weightFrom"
									:min="0"
									placeholder="从"
								/>
								<span style="padding: 0 6px">-</span>
								<a-input-number
									style="width: 40%"
									v-model:value="searchInfo.weightTo"
									:min="searchInfo.weightFrom || 0"
									placeholder="到"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'profession'" label="职业">
								<a-select
									v-model:value="searchInfo.profession"
									:options="professionList"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									allow-clear
									placeholder="请选择职业"
									style="width: 90%; margin-left: 8px"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'incomeStatus'" label="收入">
								<a-select
									v-model:value="searchInfo.incomeStatus"
									:options="incomeStatusList"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									allow-clear
									placeholder="请选择收入"
									style="width: 90%; margin-left: 8px"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'carHouseStatus'" label="车房情况">
								<a-select
									v-model:value="searchInfo.carHouseStatus"
									:options="carHouseStatusList"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									allow-clear
									placeholder="请选择车房情况"
									style="width: 90%; margin-left: 8px"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'location'" label="区域">
								<a-cascader
									v-model:value="location"
									:options="locationTree"
									placeholder="请选择区域（可选择省、市或区县）"
									:load-data="loadData"
									:fieldNames="{
										label: 'name',
										value: 'id',
										children: 'children',
									}"
									change-on-select
									allow-clear
									@blur="handleLocationChange"
									:expand-trigger="'click'"
									style="width: 90%; margin-left: 8px"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item :name="'maritalStatus'" label="婚姻状况">
								<a-select
									v-model:value="searchInfo.maritalStatus"
									allow-clear
									placeholder="请选择婚姻状况"
									style="width: 90%; margin-left: 8px"
								>
									<a-select-option
										v-for="i in maritalStatusList"
										:key="i.typeCode"
										:value="i.typeCode"
									>
										{{ i.typeName }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<a-button type="primary" @click="exportAllUserInfo">导出</a-button>
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record: any) => record.id || record.code"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ x: 'max-content', y: 420 }"
				:table-layout="'fixed'"
				:empty-text="'暂无数据'"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'source'">
						{{ getSourceName(record.source) }}
					</template>
					<template v-else-if="column.key === 'wechatGzhOpenid'">
						<a-tag :color="record.wechatGzhOpenid ? '#87d068' : 'red'">
							{{ record.wechatGzhOpenid ? '已关注' : '未关注' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'identityVerificationName'">
						{{ record.identityVerificationVo?.name || '' }}
					</template>
					<template
						v-else-if="column.key === 'identityVerificationIdCardNumber'"
					>
						{{ record.identityVerificationVo?.idCardNumber || '' }}
					</template>
					<template v-else-if="column.key === 'membershipFlag'">
						<a-tag :color="record.membershipFlag ? '#87d068' : 'red'">
							{{ record.membershipFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'membershipName'">
						{{ record.membershipName || '' }}
					</template>
					<template v-else-if="column.key === 'userMembershipStartTime'">
						{{
							record.userMembershipInfoVo?.startTime ?
								dayjs(record.userMembershipInfoVo?.startTime).format(
									'YYYY-MM-DD',
								)
							:	''
						}}
					</template>
					<template v-else-if="column.key === 'userMembershipEndTime'">
						{{
							record.userMembershipInfoVo?.endTime ?
								dayjs(record.userMembershipInfoVo?.endTime).format('YYYY-MM-DD')
							:	''
						}}
					</template>
					<template v-else-if="column.key === 'matchmakerNo'">
						{{ record.matchmakerInfoVo?.no ?? '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerPositionLevelName'">
						{{
							record.matchmakerInfoVo?.positionLevelName ||
							record.matchmakerInfoVo?.positionLevel ||
							''
						}}
					</template>
					<template v-else-if="column.key === 'matchmakerFlag'">
						<a-tag :color="record.matchmakerFlag ? '#87d068' : 'red'">
							{{ record.matchmakerFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'matchmakerName'">
						{{ record.matchmakerInfoVo?.name || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerBirthDate'">
						{{ record.matchmakerInfoVo?.birthDate || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerContactPhone'">
						{{ record.matchmakerInfoVo?.contactPhone || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerEntryDate'">
						{{ record.matchmakerInfoVo?.entryDate || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerExpertise'">
						{{ record.matchmakerInfoVo?.expertise || '' }}
					</template>
					<template v-else-if="column.key === 'matchmakerGender'">
						{{
							record.matchmakerInfoVo?.gender === '0' ? '男'
							: record.matchmakerInfoVo?.gender === '1' ? '女'
							: ''
						}}
					</template>
					<template v-else-if="column.key === 'matchmakerStatus'">
						<a-tag
							:color="record.matchmakerInfoVo?.status == 2 ? '#87d068' : 'red'"
						>
							{{ record.matchmakerInfoVo?.status == 2 ? '在职' : '离职' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'matchmakerRegion'">
						{{
							[
								record.matchmakerInfoVo?.provinceName,
								record.matchmakerInfoVo?.cityName,
								record.matchmakerInfoVo?.districtName,
							]
								.filter(Boolean)
								.join('/') || ''
						}}
					</template>
					<template v-else-if="column.key === 'matchmakerPhotoUrl'">
						<a-image
							v-if="record.matchmakerInfoVo?.photoUrl"
							:width="80"
							:src="record.matchmakerInfoVo?.photoUrl"
						/>
					</template>
					<template v-else-if="column.key === 'matchmakerWechatQrcodeUrl'">
						<a-image
							v-if="record.matchmakerInfoVo?.wechatQrcodeUrl"
							:width="80"
							:src="record.matchmakerInfoVo?.wechatQrcodeUrl"
						/>
					</template>
					<!-- 征婚档案 userProfileInfoVo 字段展示 -->
					<template v-else-if="column.key === 'userProfileInfoVoNickname'">
						{{ record.userProfileInfoVo?.nickname ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoGender'">
						{{
							record.userProfileInfoVo?.gender === '0' ? '男'
							: record.userProfileInfoVo?.gender === '1' ? '女'
							: ''
						}}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoBirthYearMonth'"
					>
						{{ record.userProfileInfoVo?.birthYearMonth ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoHeight'">
						{{ record.userProfileInfoVo?.height ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoWeight'">
						{{ record.userProfileInfoVo?.weight ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoResidenceName'">
						{{
							[
								record.userProfileInfoVo?.provinceName,
								record.userProfileInfoVo?.cityName,
								record.userProfileInfoVo?.districtName,
							]
								.filter(Boolean)
								.join('/') || ''
						}}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoMaritalStatusName'"
					>
						{{ record.userProfileInfoVo?.maritalStatusName ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoEducationLevelName'"
					>
						{{ record.userProfileInfoVo?.educationLevelName ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoProfessionName'"
					>
						{{ record.userProfileInfoVo?.professionName ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoIncomeStatusName'"
					>
						{{ record.userProfileInfoVo?.incomeStatusName ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoCarHouseStatusName'"
					>
						{{ record.userProfileInfoVo?.carHouseStatusName ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoSchoolName'">
						{{ record.userProfileInfoVo?.schoolName ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoEducationTypeName'"
					>
						{{ record.userProfileInfoVo?.educationTypeName ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoSpecialNote'">
						{{ record.userProfileInfoVo?.specialNote ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoPartnerRequirements'"
					>
						{{ record.userProfileInfoVo?.partnerRequirements ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoLoveView'">
						{{ record.userProfileInfoVo?.loveView ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoIdealPartner'">
						{{ record.userProfileInfoVo?.idealPartner ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoContactPhone'">
						{{ record.userProfileInfoVo?.contactPhone ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoZodiac'">
						{{ record.userProfileInfoVo?.zodiacName ?? '' }}
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoShowPhone'">
						<a-tag
							:color="record.userProfileInfoVo?.showPhone ? '#87d068' : 'red'"
						>
							{{ record.userProfileInfoVo?.showPhone ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'userProfileInfoVoShowWechat'">
						<a-tag
							:color="record.userProfileInfoVo?.showWechat ? '#87d068' : 'red'"
						>
							{{ record.userProfileInfoVo?.showWechat ? '是' : '否' }}
						</a-tag>
					</template>
					<template
						v-else-if="column.key === 'userProfileInfoVoAutoExchangeContact'"
					>
						<a-tag
							:color="
								record.userProfileInfoVo?.autoExchangeContact ?
									'#87d068'
								:	'red'
							"
						>
							{{ record.userProfileInfoVo?.autoExchangeContact ? '是' : '否' }}
						</a-tag>
					</template>
					<!-- 择偶要求（结构化） -->
					<template v-else-if="column.key === 'partnerReqAge'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo?.ageFrom ?
								record?.userProfileInfoVo?.userPartnerPreferencesVo.ageFrom +
								'-' +
								record?.userProfileInfoVo?.userPartnerPreferencesVo.ageTo
							:	'不限'
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqHeight'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo?.heightFrom ?
								record?.userProfileInfoVo?.userPartnerPreferencesVo.heightFrom +
								'-' +
								record?.userProfileInfoVo?.userPartnerPreferencesVo.heightTo
							:	'不限'
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqWeight'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo?.weightFrom ?
								record?.userProfileInfoVo?.userPartnerPreferencesVo.weightFrom +
								'-' +
								record?.userProfileInfoVo?.userPartnerPreferencesVo.weightTo
							:	'不限'
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqEducationLevel'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo
								?.educationLevelName || ''
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqProfession'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo
								?.professionName || ''
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqIncomeRange'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo
								?.incomeRangeName || ''
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqHousingCarStatus'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo
								?.housingCarStatusName || ''
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqMaritalStatus'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo
								?.maritalStatusName || ''
						}}
					</template>
					<template v-else-if="column.key === 'partnerReqRegion'">
						{{
							record?.userProfileInfoVo?.userPartnerPreferencesVo ?
								[
									record?.userProfileInfoVo?.userPartnerPreferencesVo
										.provinceName,
									record?.userProfileInfoVo?.userPartnerPreferencesVo.cityName,
									record?.userProfileInfoVo?.userPartnerPreferencesVo
										.districtName,
								]
									.filter(Boolean)
									.join('/')
							:	'不限'
						}}
					</template>
					<template v-else-if="column.key === 'partnerFlag'">
						<a-tag :color="record.partnerFlag ? '#87d068' : 'red'">
							{{ record.partnerFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<!-- 合伙人 offlineServiceProviderVo 字段展示 -->
					<template v-else-if="column.key === 'offlineServiceProviderVoUserId'">
						{{ record.offlineServiceProviderVo?.userId ?? '' }}
					</template>
					<template v-else-if="column.key === 'offlineServiceProviderVoType'">
						{{ record.offlineServiceProviderVo?.type ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoPartnerType'"
					>
						{{ record.offlineServiceProviderVo?.partnerType ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoPartnerTypeName'"
					>
						{{
							getPartnerName(record.offlineServiceProviderVo?.partnerType) ?? ''
						}}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoStartTime'"
					>
						{{
							record.offlineServiceProviderVo?.startTime ?
								dayjs(record.offlineServiceProviderVo?.startTime).format(
									'YYYY-MM-DD HH:mm:ss',
								)
							:	''
						}}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoEndTime'"
					>
						{{
							record.offlineServiceProviderVo?.endTime ?
								dayjs(record.offlineServiceProviderVo?.endTime).format(
									'YYYY-MM-DD HH:mm:ss',
								)
							:	''
						}}
					</template>
					<template v-else-if="column.key === 'offlineServiceProviderVoStatus'">
						{{ record.offlineServiceProviderVo?.status ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoStatusFlag'"
					>
						<a-tag
							:color="
								record.offlineServiceProviderVo?.statusFlag ? '#87d068' : 'red'
							"
						>
							{{
								record.offlineServiceProviderVo?.statusFlag ? '有效' : '无效'
							}}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'offlineServiceProviderVoName'">
						{{ record.offlineServiceProviderVo?.name ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoContactInfo'"
					>
						{{ record.offlineServiceProviderVo?.contactInfo ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoPhoneNumber'"
					>
						{{ record.offlineServiceProviderVo?.phoneNumber ?? '' }}
					</template>
					<template
						v-else-if="
							column.key === 'offlineServiceProviderVoDemandDescription'
						"
					>
						{{ record.offlineServiceProviderVo?.demandDescription ?? '' }}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoResidence'"
					>
						{{
							[
								record.offlineServiceProviderVo?.provinceName,
								record.offlineServiceProviderVo?.cityName,
								record.offlineServiceProviderVo?.districtName,
							]
								.filter(Boolean)
								.join('/') || ''
						}}
					</template>
					<template
						v-else-if="column.key === 'offlineServiceProviderVoSingleFlag'"
					>
						<a-tag
							:color="
								record.offlineServiceProviderVo?.singleFlag ? '#87d068' : 'red'
							"
						>
							{{ record.offlineServiceProviderVo?.singleFlag ? '是' : '否' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'offlineServiceProviderVoCode'">
						{{ record.offlineServiceProviderVo?.code ?? '' }}
					</template>
				</template>
			</a-table>
		</div>
	</div>
</template>
<script setup lang="ts">
import { message } from 'ant-design-vue';
import { exportAllUserInfoApi, getUserAllInfoPage } from './api/index';
import { columns, getSourceName, pageInfo, pagination, SearchInfo } from './config/index';
import { debounce, getPartnerName } from '@/utils/common';
import dayjs from 'dayjs';
import { getDictList } from '@/api/commonInfo/dictInfo/dictInfoTs';
import { getLocationTree } from '@/api/eventInfo/eventInfo/eventInfoTs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let searchInfo = ref<SearchInfo>({});

let loading = ref<boolean>(false);
let dataSource = ref<any[]>([]);

// 地区级联
const location = ref<any[]>([]);
const locationTree = ref<any[]>([]);

// 字典下拉列表
const professionList = ref<any[]>([]);
const incomeStatusList = ref<any[]>([]);
const carHouseStatusList = ref<any[]>([]);
const maritalStatusList = ref<any[]>([]);

const handleLocationChange = (_value: any) => {
	// 当选择完成时，可以在这里添加额外的处理逻辑
	// 根据选择的层级提供用户反馈
	if (location.value && location.value.length > 0) {
		const levelNames = ['省份', '城市', '区县'];
		const selectedLevel = levelNames[location.value.length - 1];
		console.log(`已选择${selectedLevel}级别`);
	}
};

const getLocationTreeInfo = async (parentId: number): Promise<any> => {
	const {
		data,
		code,
		message: messageInfo,
	} = await getLocationTree({ parentId }).catch((error: any) => {
		message.error(error?.message || '查询失败！');
	});
	if (code == '200') {
		return data;
	} else {
		message.error(messageInfo || '查询失败！');
		return [];
	}
};

const loadData = async (selectedOptions: any[]) => {
	console.log(`selectedOptions`, selectedOptions);
	const targetOption = selectedOptions[selectedOptions.length - 1];
	targetOption.loading = true;

	try {
		const children = await getLocationTreeInfo(targetOption.id);
		if (!children || children.length === 0) {
			targetOption.isLeaf = true;
			targetOption.loading = false;
			return;
		}

		// 添加"全部"选项
		const allOption = {
			id: -1, // 使用-1作为"全部"选项的特殊标识
			name: '全部',
			level: targetOption.level + 1,
			isLeaf: true,
		};

		// 将"全部"选项添加到子级列表的开头
		targetOption.children = [allOption, ...children];

		targetOption.children.forEach((item: any) => {
			// 跳过"全部"选项，因为它已经设置了正确的属性
			if (item.name === '全部') {
				return;
			}

			// 根据当前层级设置下一级的属性
			if (targetOption.level === 1) {
				// 省级，下一级是市级
				item.isLeaf = false;
				item.level = 2;
			} else if (targetOption.level === 2) {
				// 市级，下一级是区县级
				item.isLeaf = true;
				item.level = 3;
			}
		});
	} catch (error) {
		console.error('加载地区数据失败:', error);
		message.error('加载地区数据失败');
	} finally {
		targetOption.loading = false;
	}
};

const cancelQuery = (): void => {
	searchInfo.value = {};
	location.value = [];
};

const query = (): void => {
	// 将级联选中值映射回 provinceId/cityId/districtId
	if (location.value && location.value.length > 0) {
		console.log(`location.value`, location.value);

		// 处理省份ID - 省级没有"全部"选项，直接使用选择的省份ID
		searchInfo.value.provinceId = location.value[0];

		// 处理城市ID
		if (location.value[1] === -1) {
			// 选择省份下的"全部"城市
			searchInfo.value.cityId = undefined;
			searchInfo.value.districtId = undefined;
		} else if (location.value[1]) {
			// 选择了具体城市
			searchInfo.value.cityId = location.value[1];

			// 处理区县ID
			if (location.value[2] === -1) {
				// 选择城市下的"全部"区县
				searchInfo.value.districtId = undefined;
			} else if (location.value[2]) {
				// 选择了具体区县
				searchInfo.value.districtId = location.value[2];
			} else {
				searchInfo.value.districtId = undefined;
			}
		} else {
			searchInfo.value.cityId = undefined;
			searchInfo.value.districtId = undefined;
		}
	} else {
		searchInfo.value.provinceId = undefined;
		searchInfo.value.cityId = undefined;
		searchInfo.value.districtId = undefined;
	}

	console.log('查询参数:', {
		provinceId: searchInfo.value.provinceId,
		cityId: searchInfo.value.cityId,
		districtId: searchInfo.value.districtId,
	});

	getList(searchInfo.value, pagination.value);
};

// 创建防抖查询方法（300ms）
const debouncedQuery = debounce(query, 300);

// 深度监听查询条件变化，自动触发防抖查询
watch(
	() => searchInfo.value,
	() => {
		pagination.value.current = 1;
		debouncedQuery();
	},
	{ deep: true },
);

// 监听地区级联选择变化，自动触发防抖查询
watch(
	() => location.value,
	() => {
		pagination.value.current = 1;
		debouncedQuery();
	},
	{ deep: true },
);

const handleTableChange = (p): void => {
	getList(searchInfo.value, p);
};

const getList = (param: SearchInfo, cur: pageInfo): void => {
	loading.value = true;
	getUserAllInfoPage(param, cur.current, cur.pageSize)
		.then((res: any) => {
			if (res.code == '200') {
				console.log(res.data.records);
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

// 导出所有用户信息
const exportAllUserInfo = async (): Promise<void> => {
	try {
		message.loading('正在导出数据，请稍候...', 0);

		const response = await exportAllUserInfoApi(searchInfo.value);

		// 检查响应是否为blob
		if (response && response.data) {
			// 创建下载链接
			const blob = new Blob([response.data], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			});

			const url = window.URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;

			// 设置文件名
			const now = new Date();
			const timestamp =
				now.getFullYear() +
				String(now.getMonth() + 1).padStart(2, '0') +
				String(now.getDate()).padStart(2, '0') +
				'_' +
				String(now.getHours()).padStart(2, '0') +
				String(now.getMinutes()).padStart(2, '0') +
				String(now.getSeconds()).padStart(2, '0');
			link.download = `用户信息_${timestamp}.xlsx`;

			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url);

			message.destroy();
			message.success('导出成功！');
		} else {
			throw new Error('导出响应格式错误');
		}
	} catch (error) {
		message.destroy();
		console.error('导出失败:', error);
		message.error('导出失败，请重试！');
	}
};

const init = (): void => {
	// 初始化地区树（顶层）
	getLocationTreeInfo(0).then((list) => {
		if (list && list.length > 0) {
			// 设置第一级数据的层级属性
			locationTree.value = list.map((item: any) => ({
				...item,
				level: 1,
				isLeaf: false,
			}));
		} else {
			locationTree.value = [];
		}
	});
	// 加载字典（合并一次请求）
	getDictList('profession,income,assets,matrimony').then((res: any) => {
		if (res?.code == '200') {
			const list = res.data || [];
			professionList.value = list.filter(
				(i: any) => i.belongTo == 'profession',
			);
			incomeStatusList.value = list.filter((i: any) => i.belongTo == 'income');
			carHouseStatusList.value = list.filter(
				(i: any) => i.belongTo == 'assets' && i.typeCode.trim() != 'secret',
			);
			maritalStatusList.value = list.filter(
				(i: any) => i.belongTo == 'matrimony',
			);
		} else {
			message.error((res && res.message) || '查询字典失败！');
		}
	});
	getList(searchInfo.value, pagination.value);
};

init();
</script>
<style lang="less" scoped>
.page-info {
	height: 100%;
	overflow-y: auto;
}
</style>